<script lang="ts">
import { defineComponent, onMounted, ref, reactive } from "vue";
import { Order } from "../../types.ts";
import axios from "axios";
import { Search, Refresh, Plus, Edit, Delete, ArrowLeft } from '@element-plus/icons-vue';
import {ElMessage,ElMessageBox} from "element-plus";

export default defineComponent({
  name: 'AllOrders',
  computed: {
    Plus() {
      return Plus
    },
    Refresh() {
      return Refresh
    },
    Search() {
      return Search
    },
    Edit() {
      return Edit
    },
    Delete() {
      return Delete
    }
  },
  components: {
    Search, Refresh, Plus, Edit, Delete, ArrowLeft
  },
  setup() {
    const orders = ref<Order[]>([]);
    const loading = ref(false);
    const searchInput = ref('');
    const dialogVisible = ref(false);
    const currentOrder = reactive<Partial<Order>>({});
    const isEditing = ref(false);

    // 获取所有订单
    const loadOrders = async () => {
      loading.value = true;
      try {
        const response = await axios.get<Order[]>('/api/order');
        orders.value = response.data;
      } catch (error) {
        console.error('加载订单信息失败:', error);
        ElMessage.error('加载订单信息失败，请稍后重试。');
      } finally {
        loading.value = false;
      }
    };

    // 添加订单
    const addOrder = async () => {
      isEditing.value = false;
      currentOrder.orderId = 0;
      currentOrder.customerId = 0;
      currentOrder.totalPrice = 0;
      currentOrder.orderStatus = false;
      currentOrder.createdAt = new Date().toISOString();
      dialogVisible.value = true;
    };

    // 保存订单（新增或更新）
    const saveOrder = async () => {
      try {
        if (isEditing.value && currentOrder.orderId) {
          await axios.put(`/api/order/${currentOrder.orderId}`, currentOrder);
          ElMessage.success('订单更新成功');
        } else {
          await axios.post('/api/order', currentOrder);
          ElMessage.success('订单添加成功');
        }
        dialogVisible.value = false;
        await loadOrders();
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败，请稍后重试。');
      }
    };

    // 编辑订单
    const editOrder = (order: Order) => {
      Object.assign(currentOrder, order);
      isEditing.value = true;
      dialogVisible.value = true;
    };

    // 删除订单
    const deleteOrder = async (order: Order) => {
      try {
        await ElMessageBox.confirm(
            `确定要删除订单 #${order.orderId} 吗?`,
            '警告',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
        );
        await axios.delete(`/api/order/${order.orderId}`);
        ElMessage.success('订单删除成功');
        await loadOrders();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除订单失败:', error);
          ElMessage.error('删除订单失败');
        }
      }
    };

    // 搜索订单
    const searchOrders = () => {
      if (!searchInput.value) {
        loadOrders();
        return;
      }
      const searchTerm = searchInput.value.toLowerCase();
      orders.value = orders.value.filter(order =>
          order.orderId.toString().includes(searchTerm) ||
          order.customerId.toString().includes(searchTerm) ||
          order.totalPrice.toString().includes(searchTerm)
      );
    };

    // 返回上一页
    const goBack = () => {
      window.history.back();
    };

    onMounted(() => {
      loadOrders();
    });

    return {
      orders,
      loading,
      searchInput,
      dialogVisible,
      currentOrder,
      isEditing,
      loadOrders,
      addOrder,
      editOrder,
      deleteOrder,
      saveOrder,
      searchOrders,
      goBack
    };
  }
});
</script>

<template>
  <div class="order-management">
    <el-card shadow="never" class="header-card">
      <div class="header">
        <div class="title-area">
          <el-tooltip content="返回" placement="top">
            <el-button circle plain @click="goBack" class="back-button">
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
          </el-tooltip>
          <div class="title">
            <h2>订单管理</h2>
          </div>
        </div>
        <div class="actions">
          <el-input
              v-model="searchInput"
              placeholder="搜索订单ID、客户ID或金额"
              clearable
              class="search-input"
              @clear="loadOrders"
              @keyup.enter="searchOrders"
          >
            <template #append>
              <el-button :icon=Search @click="searchOrders" />
            </template>
          </el-input>
          <el-button :icon=Refresh @click="loadOrders" :loading="loading">刷新</el-button>
          <el-button type="primary" :icon=Plus @click="addOrder">添加订单</el-button>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="table-card">
      <el-table
          :data="orders"
          v-loading="loading"
          stripe
          style="width: 100%"
          empty-text="暂无订单数据"
      >
        <el-table-column prop="orderId" label="订单ID" width="120" sortable />
        <el-table-column prop="customerId" label="客户ID" width="120" sortable />
        <el-table-column prop="totalPrice" label="总金额" width="150" sortable>
          <template #default="{row}">
            ¥{{ row.totalPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="状态" width="120">
          <template #default="{row}">
            <el-tag :type="row.orderStatus ? 'success' : 'danger'">
              {{ row.orderStatus ? '已完成' : '进行中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
          <template #default="{row}">
            {{ new Date(row.createdAt).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180" sortable>
          <template #default="{row}">
            {{ row.updatedAt ? new Date(row.updatedAt).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{row}">
            <el-button size="small" :icon=Edit @click="editOrder(row)" />
            <el-button size="small" type="danger" :icon=Delete @click="deleteOrder(row)" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑订单对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditing ? '编辑订单' : '添加订单'"
        width="600px"
    >
      <el-form :model="currentOrder" label-width="120px">
        <el-form-item label="订单ID" v-if="isEditing">
          <el-input v-model="currentOrder.orderId" disabled />
        </el-form-item>
        <el-form-item label="客户ID" required>
          <el-input-number v-model="currentOrder.customerId" :min="1" />
        </el-form-item>
        <el-form-item label="总金额" required>
          <el-input-number v-model="currentOrder.totalPrice" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-switch
              v-model="currentOrder.orderStatus"
              active-text="已完成"
              inactive-text="进行中"
          />
        </el-form-item>
        <el-form-item label="创建时间" v-if="isEditing">
          <el-date-picker
              v-model="currentOrder.createdAt"
              type="datetime"
              disabled
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrder">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-management {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.table-card {
  border-radius: 8px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.title-area {
  display: flex;
  align-items: center;
  gap: 15px;
}

.title h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

.back-button {
  width: 36px;
  height: 36px;
  font-size: 16px;
  color: var(--el-color-primary);
  border: 1px solid var(--el-border-color);
  transition: all 0.3s;
}

.back-button:hover {
  color: var(--el-color-primary-light-2);
  border-color: var(--el-color-primary-light-5);
  transform: translateX(-2px);
}

.actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  width: 280px;
}

.el-table {
  margin-top: 10px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }

  .actions {
    width: 100%;
  }

  .search-input {
    width: 100%;
  }
}
</style>